(function(a, ng) {
    'use strict';
    var app = a.adminApp;

    app.directive('isEquals', [
        function() {
            return {
                require: 'ngModel',
                link: function(scope, elem, attrs, controller) {
                    var firstElement = attrs.isEquals;
                    elem.add(firstElement).on('keyup', function(i) {
                        scope.$apply(function() {
                            var v = elem.val() === $(firstElement).val();
                            controller.$setValidity('isequals', v);
                        });
                    });
                }
            };
        }]);
    app.directive('cocBreadcumbs', function($location, $route, $rootScope) {
        var currentUrl = '#' + $location.path();
        return {
            replace: true,
            restrict: 'EACM',
            priority: 0,
            scope: true,
            templateUrl: URL_ADMIN + '/views/breadcumbs',
            link: function(scope, elem, attrs, ctrl) {
            },
            controller: function($scope, $element, $attrs) {

            }
        };
    });

    app.directive('modelChangeBlur', function() {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function(scope, elem, attr, ngModelCtrl) {
                if (attr.type === 'radio' || attr.type === 'checkbox')
                    return;
                elem.unbind('input').unbind('keydow').unbind('change');
                elem.bind('blur', function() {
                    scope.$apply(function() {
                        ngModelCtrl.$setViewValue(elem.val());
                    });
                });

            }
        };
    });

    app.directive('cocGrid', function($compile, cocGridDataFactory, notificationFactory) {

        return {
            restrict: 'A',
            replace: false,
            priority: 5,
            scope: true,
            require: '?ngModel',
            templateUrl: URL_ADMIN + 'views/dataGrid.grid',
            controller: ['$scope',
                function($scope) {
                    $scope.getDataCall = function(key, value, obj) {
                        if (typeof $scope.callbackColumns[key] === 'undefined') {
                            return value;
                        }

                        var fn = $scope.callbackColumns[key];

                        return $scope[fn](key, value, obj);

                    };

                }],
            link: function($scope, $element, $attrs) {
                var defaults = {
                    key: 'id',
                    buttons: {top: [], line: [], footer: []},
                    actions: [],
                    unsets: {
                        'add': false,
                        'delete': false,
                        'edit': false
                    },
                    orderBy: {
                        field: 'ID',
                        asc: true
                    }
                    ,
                    GridLoading: true,
                    callbacks: {
                        beforeRender: function() {

                        },
                        afterRender: function() {

                        }
                    },
                    urlAdd: !1,
                    urlEdit: !1

                };

                var
                        $options = $attrs.datagridOptions || {},
                        options = ng.extend(defaults, $scope.$eval($options));



                $scope.objects = {};
                $scope.lookups = {};
                $scope.callbackColumns = {};
                $scope.object = {};
                $scope.columns = ng.fromJson($attrs.columns);
                $scope.unsets = options.unsets;
                $scope.filter = '';
                $scope.GridLoading = options.GridLoading;
                $scope.key = options.key;
                $scope.add = options.urlAdd;
                $scope.edit = options.urlEdit;
                $scope.orderBy = options.orderBy;

                var $docScope = ng.element(document).scope();
                // remove options actions
                $scope.actionsDataGrid = options.actions || [];

                $scope.buttons = options.buttons || [];
                $scope.setLookupData = function() {
                    for (var i = 0; i < $scope.columns.length; i += 1) {
                        var c = $scope.columns[i];
                        if (c.lookup && !$scope.hasLookupData(c.lookup.table)) {
                            cocGridDataFactory(c.lookup.table).query(function(data) {
                                $scope.setIndividualLookupdata(c.lookup.table, data);
                            });
                        }
                        if (c.callback) {
                            $scope.setCallValue(c.name, c.callback);
                        }
                    }
                };
                $scope.resetCocDataGrid = function(table) {
                    $scope.setIndividual(table, {});
                    $scope.setLookupData();
                };

                $scope.setCallValue = function(key, callback) {
                    $scope.callbackColumns[key] = callback;
                };

                $scope.getLookupData = function(table) {
                    return typeof table === 'undefined' ? null : $scope.lookups[table.toLowerCase()];
                };
                $scope.setIndividual = function(table, data) {

                    $scope.lookups[table.toLowerCase()] = data;
                };

                $scope.hasLookupData = function(table) {
                    return !$.isEmptyObject($scope.getLookupData(table));
                };

                $scope.getLookupValue = function(lookup, key) {

                    var data = $scope.getLookupData(lookup.table);
                    if (typeof data !== 'undefined') {
                        for (var i = 0, max = data.length; i < max; i += 1) {
                            if (data[i][lookup.key] === key) {
                                return data[i][lookup.value];
                            }
                        }
                    }

                    return '';
                };
                $scope.toggleAddMode = function() {
                    $scope.addMode = !$scope.addMode;
                    $scope.object = {};
                    // notificationFactory.modalBox();
                };
                $scope.toggleEditMode = function(object) {
                    $scope.editMode = !$scope.editMode;
                };
                var successCallback = function(e, cb) {
                    notificationFactory.success();
                    $docScope.$broadcast('lookupDataChange', [$attrs.table]);
                    $scope.getData(cb);
                };
                var successPostCallback = function(e) {
                    successCallback(e, function() {
                        $scope.toggleAddMode();
                    });
                };

                $scope.$on('lookupDataChange', function(scope, table) {
                    $scope.resetCocDataGrid(table[0]);
                });
                var errorCallback = function(e) {
                    notificationFactory.error(e.data.ExceptionMessage);
                };
                $scope.addObject = function() {
                    cocGridDataFactory($attrs.table).save($scope.object, successPostCallback, errorCallback);
                };
                $scope.deleteObject = function(object) {
                    notificationFactory.confirm({
                        message: 'Success',
                        callbackConfirm: function() {
                            var params = {};
                            // getParams();
                            params.id = object[$scope.key];
                            cocGridDataFactory($attrs.table)
                                    .delete(params, successCallback, errorCallback);

                        }
                    });

                };

                $scope.gridCall = function(fn, obj) {
                    $scope[fn](obj);
                };

                $scope.updateObject = function(object) {
                    var params = options.params || {};
                    params.id = object.id;
                    cocGridDataFactory($attrs.table).update(params, object, successCallback, errorCallback);
                };

                $scope.getData = function(cb) {
                    var params = options.params || {};

                    options.callbacks.beforeRender();
                    cocGridDataFactory($attrs.table).query(params, function(data) {
                        $scope.objects = data;
                        if (cb) {
                            cb();
                        }
                        ;
                    });
                };

                $scope.setOrderBy = function(field) {
                    var asc = $scope.orderBy.field === field ? !$scope.orderBy.asc : true;
                    $scope.orderBy = {
                        field: field,
                        asc: asc
                    };
                };

                $scope.getData(function() {
                    $scope.setLookupData();

                    $scope.GridLoading = false;
                    $scope.showGrid = true;
                });

            }

        };
    });
    app.directive('gridCallback', function() {

        return {
            link: function($scope, $element, $attrs) {
                var txt = $scope.$eval($attrs.gridCallValue), pattern = /<(.|\n)*?>/;
                if (pattern.test(txt)) {

                    $element.html(txt);
                } else {
                    $element.text(txt);
                }
                ;
            }
        };

    });
    app.filter('extractDate', function() {
        return function(str) {
            var patternUS = /[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}/gi, dateExplode, date = str;
            if (patternUS.test(str)) {
                dateExplode = str.split(" ");
                dateExplode = dateExplode[0].split('-');
                dateExplode.reverse();
                date = dateExplode.join('/');
            }

            return date;
        };

    });

    app.filter('formater', function() {

        return function($str, $tp) {

            switch ($tp) {

                case 'fone':
                case 'default':

                    return $str.substring(0, 1);
                    break;

            }

        };
    });

    app.directive('cocMask', function($window) {

        return {
            restrict: 'A',
            require: '^?ngModel',
            link: function(scope, elem, attrs, ctrl) {

                var moment = $window.moment;
                $(elem).mask(attrs['format']);

                attrs.$observe('coc-format', function(nValue) {

                });
            }
        };

    });

    app.directive('cocFocusOut', function() {
        return {
            restrict: 'A',
            link: function(scope, elem, attr) {

                elem.bind('focusout', function() {
                    scope.$apply(attr.cocFocusOut);
                    // scope.$watch(attr.cocFocusOut, function(fn, o) {
                    // console.log(fn);
                    // });
                });

            }
        };
    });

    app.directive('cocEditor', [
        function() {
            return {
                require: '?ngModel',
                link: function($scope, elm, attr, ngModel) {

                    var ck = CKEDITOR.replace(elm[0]);

                    ck.on('pasteState', function() {
                        $scope.$apply(function() {
                            ngModel.$setViewValue(ck.getData());
                        });
                    });

                    ngModel.$render = function(value) {
                        ck.setData(ngModel.$modelValue);
                    };
                }
            };
        }]);
    app.filter('replaceValueId', function() {

        return (function($value, $id) {
            if ($id !== '' && $id !== undefined) {
                return $value.replace(/:[a-z]{1,}/gi, $id);
            }
        });

    });

    app.directive('cocClickPrevent', function() {
        return {
            restrict: 'A',
            link: function($scope, $element, $attrs) {
                $element.on('click.ClickPrevent', function(e) {
                    if ($attrs.ngClick || $attrs.dataNgClick || $attrs.href === '' || $attrs.href == '#') {
                        e.preventDefault();
                        e.stopPropagation();
                    }

                });

            }
        };

    });

    app.directive('cocFileUpload', ['cocFileUploader', 'browser','notificationFactory','cocLoading',
        function(cocFileUploader, browser, notificationFactory,cocLoading) {
            var $$template = '<span><input type="file" style="opacity:0;display:none;" class="hide"  />' + '<label class="btn btn-danger" ng-click="onFileSelect()">{{buttonLabelFile}}</label> &nbsp;' + '<a href="#" class="btn btn-success" ng-disabled="showButtonStart" ng-show="showAutoComplete" ng-click="initializeUploadFile()" coc-click-prevent>' + '{{buttonLabelSend}}</a></span>';
            return {
                replace: true,
                restrict: 'AE',
                scope: {
                    'buttonLabelFile': '@',
                    'buttonLabelSend': '@',
                    'urlUpload': '@',
                    'autoUpload': '@',
                    'onDone': '&',
                    'onProgress': '&',
                    'onError': '&',
                    'onGetDataExtra': '&'
                },
                template: $$template,
                compile: function compile(tElement, tAttrs, transclude) {
                    var fileInput = ng.element(tElement.children()[0]), fileLabel = ng.element(tElement.children()[1]);

                    return function postLink(scope, $e, attrs) {
                        scope.files = [];
                        scope.showButtonStart = true;
                        scope.showAutoComplete = scope.autoUpload == 'true' ? false : true;
                        $e.bind('change', function(e) {
                            if (!e.target.files.length) {
                                return;
                            }
                            scope.files = [];
                            var tooFiles = [];
                            var file = e.target.files['0'];
                            scope.files.push(file);

                            if (scope.autoUpload === 'true') {
                                scope.initializeUploadFile();
                            } else {

                                if (browser.agent() != 'ie' && browser.agent() != null) {
                                    scope.$apply(function() {
                                        scope.showButtonStart = false;
                                    });
                                } else {
                                    scope.showButtonStart = false;
                                }
                            }

                        });
                        scope.onFileSelect = function(e) {
                            fileInput.trigger('click');
                        };
                        scope.initializeUploadFile = function() {
                            var data = null;
                            
                            if (scope.onGetDataExtra()) {
                                data = scope.onGetDataExtra();
                            }
                            
                            cocLoading.trigger();
                            cocFileUploader.post(scope.files, data, function(complete) {
                                
                                scope.onProgress({
                                    percentDone: complete
                                });
                            }).to(scope.urlUpload).then(function(resp) {
                                cocLoading.trigger();
                                scope.onDone({
                                    files: scope.files,
                                    data: resp.data,
                                    obj: resp.obj
                                });
                                scope.showButtonStart = true;
                            }, function(error) {
                               
                                scope.onError({
                                    files: scope.files,
                                    type: 'UPLOAD_ERROR',
                                    msg: error
                                });

                            });
                            resetAll();
                        };

                        function resetAll() {
                            angular.element(fileInput).val(null);
                        }
                        ;

                    };

                }
            };

        }]);

    app.directive('cocAutoCompleteCep', [
        function($compile) {
            var $cTemplate = '<div><div class="form-group row">'
                    + '<div class="col-md-2 col-xs-3">'
                    + '<label for="InputTipo" >CEP</label>'
                    + '<input ng-model="CEP" name="CEP"'
                    + 'class="form-control"' + 'ng-change="onChange()"'
                    + 'ui-mask="99999-999"'
                    + '/>'
                    + '</div>'
                    + '<div class="col-md-5 col-xs-8">'
                    + '<label for="InputTipo" >Logradouro</label>'
                    + '<input ng-model="LOGRADOURO" name="LOGRADOURO"'
                    + 'class="form-control disabled"'
                    + 'maxlength="15"'
                    + 'disabled="true"/></div>'
                    + '<div class="col-md-1 col-xs-2">'
                    + '<label for="InputTipo" >Numero</label>'
                    + '<input ng-model="NUMERO" name="NUMERO"'
                    + 'class="form-control " maxlength="10" /></div>'
                    + '<div class="col-md-2 col-xs-3">'
                    + '<label for="InputTipo" >Complemento</label>'
                    + '<input ng-model="COMPLEMENTO" name="COMPLEMENTO" class="form-control "'
                    + 'maxlength="10" /></div></div>'
                    + '<div class="form-group row">'
                    + '<div class="col-md-3 col-xs-4">'
                    + '<label for="InputTipo" >Bairro</label>'
                    + '<input ng-model="BAIRRO" name="BAIRRO" class="form-control"	disabled="true" />'
                    + '</div>'
                    + '<div class="col-md-3 col-xs-4">'
                    + '<label for="InputTipo" >Cidade</label>'
                    + '<input ng-model="CIDADE" name="CIDADE" class="form-control" maxlength="20" disabled="true"/>'
                    + '</div>'
                    + '<div class="col-md-1 col-xs-2">'
                    + '<label for="InputTipo" >Estado</label>'
                    + '<input ng-model="UF" name="UF" class="form-control" maxlength="10"	disabled="true"/>'
                    + '</div>'
                    + '</div></div>';

            return {
                require: 'ngModel',
                restrict: 'AE',
                replace: true,
                template: $cTemplate,
                scope: {
                    urlGetData: '@'

                },
                link: function(scope, $ele, $attrs, ngModel) {

                    scope.$watch(function() {
                        return ngModel.$modelValue;
                    },
                            function(modelValue) {
                                if (modelValue) {
                                    console.log(modelValue);
                                }
                                ;

                            }

                    );

                }
            };

        }]);

    /*
     * CocToolTip @dependencies bootstrap 3.0
     * 
     */
    app.directive('cocToolTip', function() {

        return {
            link: function($scope, $ele, $attrs) {
                var defaults = {
                    animation: true
                }, op = {};

                if ($attrs.title || $attrs.dataTitle) {
                    op = ng.extend(defaults, ng.fromJson($attrs.optionsToolTip) || {});
                    $ele.tooltip(op);

                }
                ;

            }};


    });

    app.directive('cocNotifications', function($http, $interval) {

        var tpl = '<li class="dropdown notifications-menu">'
                + '<a href="#" target="_self" class="dropdown-toggle" data-toggle="dropdown">'
                + '<i class="{{iconClass}}"></i>'
                + '<span class="label label-warning">{{notifications.length}}</span>'
                + '</a>'
                + '<ul class="dropdown-menu">'
                + '<li class="header">Novas {{notifications.length}} mensagens</li>'
                + '<li>'
                + '<ul class="menu">'
                + '<li ng-repeat="not in notifications">'
                + '<a ng-if="not.url != \'\' " href="{{not.url}}"><i class="fa fa-warning danger"></i> {{$index + 1}} - {{not.message}}</a>'
                + '<span ng-if="not.url>{{$index + 1}} - {{not.message}}</span>'
                + '</li>'
                + '</ul>'
                + '</li>'
                + '</ul>'
                + '</li>';


        return {
            template: tpl,
            replace: true,
            scope: true,
            link: function(scope, elem, attrs) {

                var options = {
                    time: 4000,
                    url: !1,
                    class_icon: "fa fa-envelope"
                };
                if (attrs.options) {
                    options = ng.extend(options, ng.fromJson(attrs.options) || {});

                }


                function load() {
                    $http.get(options.url).success(function(data) {
                        scope.notifications = data;
                    });
                }
                ;

                scope.notifications = [];
                scope.iconClass = options.class_icon;
                if (options.url) {
                    /*
                     $interval(function(){
                     load();
                     },options.time);
                     // init load data
                     */
                    load();
                }
                ;



            }


        };


    });






})(cocApp, angular);

